<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-12-19
 * Time: 下午3:33
 */

namespace Common\Controller;
use Think\Auth;
use Think\Controller;
use Think\Upload;


class AdminCommonController extends CommonController {
    protected $manage_id;
    protected $isSysAdmin = true;//是否为超级管理员
    protected $auth;

    protected function _initialize(){
        //异常处理
        set_exception_handler(function($exception){
            file_put_contents('systemerror.log',toDate(NOW_TIME,'Y-m-d H:i:s').":".$exception->getMessage()."\n",FILE_APPEND);//记录系统错误日志
            if(IS_AJAX){
                $this->returnData('系统错误');
            } else {
                toErrorPage();
            }
        });
        
        $this->manage_id = $_SESSION[C('USER_AUTH_KEY')];
        if(empty($this->manage_id)){//登录认证
            redirect('/Public/login');
        }

        $this->auth = new Auth();//实例化Auth
        if(!$_SESSION['administrator']){//超级管理员跳过权限认证
            $this->isSysAdmin = false;
            //权限认证
            if(ACTION_NAME == 'return_iframe' || ACTION_NAME == 'uploadredirect' || ACTION_NAME == 'jqueryuploadredirect' || ACTION_NAME == 'getLocation'){

            }else{
                //$status = $this->auth->check(MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME,$this->manage_id);
                $status = true;
                if(!$status){
                    if(IS_AJAX){
                        $jsHtml = <<<EOF
<script type="text/javascript">alert("非法操作,你没有此操作的权限");location.reload();</script>
EOF;

                        echo $jsHtml;
                    }else{
                        $this->error('非法操作,你没有此操作的权限');
                    }
                    exit;
                }
            }
        }

        //获取当前管理员权限列表
        if($_SESSION['role_id']){
            $cache = S(C('DB_PREFIX').'_role_auth_list_'.$_SESSION['role_id']);
        }else{
            $cache = S(C('DB_PREFIX').'_auth_list_'.C('MANAGE_id'));
        }
        if($cache){
            $datas = $cache;
        }else{
            $datas = $this->auth->getRoleAuthList($this->manage_id);
            if($_SESSION['role_id']){
                S(C('DB_PREFIX').'_role_auth_list_'.$_SESSION['role_id'],$datas);
            }else{
                S(C('DB_PREFIX').'_auth_list_'.C('MANAGE_id'),$datas);
            }
        }
        $this->assign('datas',$datas);
    }

    /**
     * 记录后台操作日志
     */
    protected function addHistoryLog($detail){
        if(empty($detail)) return false;
        $opearURL = MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME;
        $data = array(
            'nickname'=>$_SESSION['account'],
            'detail'=>$detail,
            'ip'=>get_client_ip(),
            'ctime'=>NOW_TIME,
            'url'=>$opearURL,
            'agent'=>getBrowser(),
            'uid'=>$_SESSION[C('USER_AUTH_KEY')],
        );

        D('Admin/ManageLog')->addLog($data);
    }

    /**
     * 保存配置
     */
    public function saveConfig() {
        if(empty($_POST['systemdata_list']) || empty($_POST['systemdata_key'])){
            $this->error('保存失败~!');
        }
        $key = $_POST['systemdata_list'].":".$_POST['systemdata_key'];
        $cache_id = '_xdata_lget_'.$_POST['systemdata_list'];

        //判断条件
        $map = array();
        $map['list'] = $_POST['systemdata_list'];
        $map['key'] = $_POST['systemdata_key'];

        unset($_POST['systemdata_list'], $_POST['systemdata_key']);

        //要更新的数据
        $data = array();
        $data['update_time'] = time();
        $data['value'] = serialize($_POST);

        $system_date = M('system_data_config');
        if($system_date->where($map)->count('id')) {
            $status = D('Xdata')->put($key,$_POST);
        } else {
            $data = $data + $map;
            $status = $system_date->add($data);
        }
        if($status) {
            S($cache_id, null);
            $this->returnData('保存成功~!',1);
        } else {
            $this->returnData('保存失败~!');
        }
    }

    public function _empty(){
        toErrorPage();
    }

    protected function _upload($id,$isEdit=false,$alias='special_html'){
        if($_FILES['specialHtml']){
            $attach = get_attach($alias);//获取附件配置
            if(empty($attach)){
                $this->returnData('不存在此附件配置');
            }

            $uploadConfig = array();
            $uploadConfig['autoSub'] = false;
            $uploadConfig['exts'] = $attach['extension'];
            $uploadConfig['maxSize'] = intval($attach['max_size']) * 1024 * 1024;//最大允许上传文件大小
            $uploadConfig['rootPath'] = ROOT_PATH;
            $uploadConfig['savePath'] = $attach['dir_path'].$id.'/';

            $upload = new Upload($uploadConfig); // 实例化上传类
            $ret = $upload->uploadOne($_FILES['specialHtml']);
            if(!$ret){
                $this->returnData($upload->getError());
            } else {
                //上传成功
                require(APP_PATH.'Common/Vendor/PclZip.class.php');
                $zip = new \PclZip(ROOT_PATH.$attach['dir_path'].$id.'/'.$ret['savename']);
                $res = $zip->extract(PCLZIP_OPT_PATH,ROOT_PATH.$attach['dir_path'].$id.'/');
                if(!$res){
                    $this->returnData('文件解压失败');
                }
                @unlink(ROOT_PATH.$attach['dir_path'].$id.'/'.$ret['savename']);
            }
            return true;
        } else if(!$isEdit) {
            $this->returnData('请上传专题页面HTML');
        }
    }
} 